package com.biostime.springdraw.modules.sd.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.biostime.springdraw.common.persistence.Page;
import com.biostime.springdraw.common.service.CrudService;
import com.biostime.springdraw.common.utils.StringUtils;
import com.biostime.springdraw.modules.sd.dao.SectionDao;
import com.biostime.springdraw.modules.sd.dto.DistributedAwardDto;
import com.biostime.springdraw.modules.sd.entity.Award;
import com.biostime.springdraw.modules.sd.entity.Section;

/**
 * 奖品阶段表Service
 * @author king
 * @version 2016-01-18
 */
@Service
@Transactional
public class SectionService extends CrudService<SectionDao, Section> {
	
	@Autowired
	private AwardService awardService;
	@Autowired
	private WinnerService winnerService;
	@Autowired
	private ShareawardService shareawardService;
	
	@Transactional
	public String saveSection(Section entity) {
		List<Award> awards = awardService.findList(new Award());
		List<Integer> awardnums = entity.getAwardnums();
		Section section = new Section();
		section.setName(entity.getName());
		List<Section> list =  findListByName(section);
		int shareNum = 0;
		if(list != null && !list.isEmpty()){
			for(int j = 0;j<list.size();j++){
				if(awardService.get(String.valueOf(list.get(j).getAwardId())).getAwardtype().getType().equals("moviecode")){					
					shareNum = list.get(j).getAmount();
				}		
			}	
		}
			
		/**
		 * 积分抽奖数量+分享抽奖数量＜真·库存
		 * 真·库存=总数-已经中走的-已经分享出去（未过期）里未抽走的
		 */
		Award award= null;
		for (int i = 0; i < awards.size(); i++) {
			award = awards.get(i);
			
			//设置真库存
			String sectionCode = entity.getCode();
			int shareExistsAward = shareawardService.shareExitsOneAward(sectionCode, awards.get(i).getId()); 
			award.setRealStock(award.getAmount()-winnerService.getWinnerCount(award) - shareExistsAward); 
			
			if(award.getIsShare().equals("1")){ 
				award.setShareNum(shareNum); 
			}
			
			logger.info("真库存："+award.getRealStock()+"---"+"积分抽奖数："+(awardnums.get(i)) +"---分享抽奖数："+award.getShareNum());
			
			if(award.getRealStock() < (awardnums.get(i)) + award.getShareNum()){ 
				return "奖品编号:"+award.getId()+"设置积分抽奖数量+分享抽奖数量不能大于真库存数量";
			}

		}
		if(entity.getCode() != null){
			List<DistributedAwardDto> awardDtoList= winnerService.getSectionAwards(entity.getCode(),0);		 
			for ( int i = 0 ; i<awards.size() ;i++ ) {
				for(DistributedAwardDto awardDto : awardDtoList){
						if(awards.get(i).getId().equals(String.valueOf(awardDto.getAwardId())) && 
								awardnums.get(i) < awardDto.getSum()){
							return "设置抽奖数不能小于已分发数量";
						}
				}				
			}
		}
	
		for(Section award2 : list){
			delete(award2);
		}
	
		String code = String.valueOf(System.currentTimeMillis());
		for ( int i = 0 ; i<awardnums.size() ;i++ ) {
			if(awardnums.get(i) != null){
				entity.setAwardId(Integer.valueOf(awards.get(i).getId()));
				entity.setAmount(awardnums.get(i));
				entity.setIsNewRecord(true);
				if(entity.getCode() != null && !entity.getCode().equals("")){
					entity.setCode(entity.getCode());
				}else{
					entity.setCode(code);
				}
				super.save(entity);
			}
		}
		
		return "保存成功";
	}
	
	public List<Section> findListByName(Section entity){
		return dao.findListByName(entity);
	}
	
	@Override
	public List<Section> findList(Section entity) {
		return dao.findList(entity);
	}
	
	@Override
	public Page<Section> findPage(Page<Section> page, Section entity) {
		entity.setPage(page);
		List<Section> list = getListNameGroup(entity);
		if(entity != null && !StringUtils.isEmpty(entity.getName())){
			String name = entity.getName();
			List<Section> listByName = new ArrayList<Section>();
			for(Section section : list){
				if(section.getName().indexOf(name) >= 0){
					listByName.add(section);
				}
			}
			page.setList(listByName);
			return page;
		}
		page.setList(list);
		return page;
	}
	
	/**
	 * 根据抽奖名称进行分组 分装 
	 * 其中返还的list中有一个或多个抽奖名称不同的Section 
	 * section中含有一个SectionList 是所有同名集合
	 * 该section name 和 id 都取SectionList里的第一个
	 * @param entity
	 * @return
	 */
	public List<Section> getListNameGroup(Section entity){
		List<Section> sections = super.findList(null);
		List<String> nameList =  new ArrayList<String>();
		for(Section award : sections ){
			nameList.add(award.getName());
		}
		HashSet<String> nameSet = new HashSet<String>(nameList);
		nameList.clear();
		nameList.addAll(nameSet);
		sections.clear();
		for(String name : nameList){
			Section section = new Section();
			section.setName(name);
			section.setSections(findListByName(section));
			section.setId(section.getSections().get(0).getId());
			section.setStartOn(section.getSections().get(0).getStartOn());
			section.setEndOn(section.getSections().get(0).getEndOn());
			sections.add(section);
		}
		return sections;
	}
	
	public List<Section> betweenDate(Section section){
		return dao.betweenDate(section);
	}
	
	public Section getByName(Section section){
		return dao.getByName(section);
	}
	
}
